package deployr.cli;

import deployr.core.*;
import deployr.domain.*;

public class CreateProjectUpdateResponder extends Responder {

	private final Workspace workspace;
	private final Projects projects;

	public CreateProjectUpdateResponder( Workspace workspace, Projects projects) {
		this.workspace = workspace;
		this.projects = projects;
	}
	
	@Override
	protected boolean shouldRespond(String method, String requestURI) {
		return "POST".equals(method) && requestURI.matches(".*/projects/.*/updates.*");
	}
	
	@Override
	protected Result respondTo(String method, String requestURI, Input input) {
		
		String projectKey = requestURI.replaceAll(".*/projects/", "").replaceAll("/updates.*", "");

		IProject project = projects.select(projectKey);
		if(notFound(project)) return new Result(404);
		
		IUpdate update = project.createUpdate();

		if(notFound(project)) return new Result(404);
		workspace.store(update);
		
		return new Result(200, update.getUpdateKey());
	}

}
